<?php
/**
 * 根据$_REQUEST['u']来解析短地址，适合几乎所有的短地址服务
 * 
 * author: corrie
 * update:2009-06-24
 */


$ha = new HeaderAnalysis ( $_REQUEST ['u'] );
$array = $ha->lines;
$status = $ha->status;
echo "源地址：" . $_GET ['u'] . "<br />";
if (( int ) $array ['Status-Code'] >= 300) {
	if ($array ['Location'] != $_REQUEST ['u']) {
		echo "真实地址：" . $array ['Location'];
	} else {
		echo "无转向地址";
	}
} else {
	echo "未知的地址";
}

$ha->debug ();



class HeaderAnalysis {
	private $_headerHtml;
	public $status;
	public $lines;
	private $_ch;
	
	function __construct($url) {
		try {
			$this->_ch = $ch = curl_init ();
			curl_setopt ( $ch, CURLOPT_URL, $url );
			curl_setopt ( $ch, CURLOPT_HEADER, 1 );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_NOBODY, 1 );
			$this->_headerHtml = curl_exec ( $ch );
		} catch ( Exception $e ) {
			throw $e;
			exit ( 'CURL NOT SUPPORTED!' );
		}
		$this->status = $this->get_status ();
		$this->array = $this->get_array ();
	}
	
	function get_status() {
		if ($this->_headerHtml != '') {
			$arr = explode ( "\r\n", $this->_headerHtml );
			preg_match ( '/HTTP\/1.1 ([0-9]+) /', $arr [0], $matchs );
			return $matchs [1];
		} else {
			return false;
		}
	}
	
	function get_array() {
		if ($this->_headerHtml != '') {
			$arr = explode ( "\r\n", $this->_headerHtml );
			for($i = 0; $i < count ( $arr ); $i ++) {
				if ($i == 0) {
					$statsarr = explode ( " ", $arr [0] );
					$array ['Status-Code'] = $statsarr [1];
					$array ['Status-Text'] = $statsarr [2];
					$array ['Agreement'] = $statsarr [0];
				} else {
					$rowarr = explode ( ": ", $arr [$i] );
					if (isset ( $rowarr [0] ) && $rowarr [0] != '' )
						$array [$rowarr [0]] = isset ( $rowarr [1] ) && trim ( $rowarr [1] ) != '' ? $rowarr [1] : '';
				}
			}
			$this->lines = $array;
		} else {
			return array ();
		}
	}
	
	function debug() {
		echo "<pre>";
		print_r ( $this->lines );
		echo "</pre>";
	}
}
?>